const mongoose = require("mongoose");
const { Schema } = mongoose;

// 订单商品 Schema
const OrderItemSchema = new Schema({
  productId: {
    type: Schema.Types.ObjectId,
    ref: "Product",
    required: true,
  },
  typeId: {
    type: Schema.Types.ObjectId,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  photo: {
    type: String,
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
  price: {
    type: String,
    required: true,
  },
  quantity: {
    type: Number,
    required: true,
  },
});

// 订单 Schema
const OrderSchema = new Schema(
  {
    user: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    username: {
      type: String,
      required: true,
    },
    orderNumber: {
      type: String,
      required: true,
      unique: true,
    },
    items: [OrderItemSchema],
    totalAmount: {
      type: String,
      required: true,
    },
    paidAmount: {
      type: String,
      default: "0",
    },
    shippingAddress: {
      type: String,
      required: true,
    },
    trackingNumber: {
      type: String,
      default: "",
    },
    shippingStatus: {
      type: String,
      enum: ["未付款", "未发货", "运输中", "订单完成", "已取消"],
      default: "未付款",
    },
    estimatedDelivery: {
      type: Date,
    },
    isDelivered: {
      type: Boolean,
      default: false,
    },
    isRefunded: {
      type: Boolean,
      default: false,
    },
    isPaid: {
      type: Boolean,
      default: false,
    },
    createdAt: {
      type: Date,
      default: Date.now,
    },
    updatedAt: {
      type: Date,
      default: Date.now,
    },
  },
  { versionKey: false }
);

module.exports = mongoose.model("Order", OrderSchema);
